package cn.csg.iotplatform.module.system.service.project;

import cn.csg.iotplatform.framework.common.enums.CommonStatusEnumx;
import cn.csg.iotplatform.framework.common.pojo.PageResult;
import cn.csg.iotplatform.framework.common.util.object.BeanUtils;
import cn.csg.iotplatform.framework.web.core.util.WebFrameworkUtils;
import cn.csg.iotplatform.module.system.controller.admin.project.vo.*;
import cn.csg.iotplatform.module.system.dal.dataobject.dept.DeptDO;
import cn.csg.iotplatform.module.system.dal.dataobject.manufacturer.ManufacturerDO;
import cn.csg.iotplatform.module.system.dal.dataobject.projectcopy.ProjectDO;
import cn.csg.iotplatform.module.system.dal.dataobject.user.AdminUserDO;
import cn.csg.iotplatform.module.system.dal.mysql.projectcopy.ProjectMapper;
import cn.csg.iotplatform.module.system.service.dept.DeptService;
import cn.csg.iotplatform.module.system.service.manufacturer.ManufacturerService;
import cn.csg.iotplatform.module.system.service.user.AdminUserService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import static cn.csg.iotplatform.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.csg.iotplatform.module.system.enums.ErrorCodeConstants.PROJECT_NOT_EXISTS;

/**
 * 项目信息 Service 实现类
 *
 * @author 系统管理员
 */
@Service
@Validated
public class ProjectServiceImpl implements ProjectService {

    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private DeptService deptService;
    @Resource
    private ManufacturerService manufacturerService;
    @Resource
    private AdminUserService adminUserService;

    @Override
    public String createProject(ProjectSaveReqVO createReqVO) {
        // 插入
        ProjectDO project = BeanUtils.toBean(createReqVO, ProjectDO.class);
        project.setId(IdUtil.fastSimpleUUID());
        projectMapper.insert(project);
        // 返回
        return project.getId();
    }

    @Override
    public void updateProject(ProjectSaveReqVO updateReqVO) {

        ProjectDO projectDO =  projectMapper.selectById(updateReqVO.getId());
        // 校验存在
        if (projectDO == null) {
            throw exception(PROJECT_NOT_EXISTS);
        }
        // 更新
        ProjectDO updateObj = BeanUtils.toBean(updateReqVO, ProjectDO.class);
        projectMapper.updateById(updateObj);
        if(!updateObj.getProjectName().equals(projectDO.getProjectName())) {
            // 更新设备项目名称
            projectMapper.updateDeviceBase(updateObj.getId(), updateObj.getProjectName());
        }
    }

    @Override
    public void deleteProject(String id) {
        // 校验存在
        validateProjectExists(id);
        // 删除
        projectMapper.deleteById(id);
    }

    @Override
    public void deleteBatchProject(String ids) {
        projectMapper.deleteBatchIds(StrUtil.split(ids,","));
    }

    @Override
    public ProjectUniqueRespVO checkProjectNoAndName(ProjectUniqueReqVO reqVO) {
        ProjectUniqueRespVO respVO = ProjectUniqueRespVO.builder().build();
        respVO.setProjectNoCount(projectMapper.selectCount(ProjectDO::getProjectNo,reqVO.getProjectNo()));
        respVO.setProjectNameCount(projectMapper.selectCount(ProjectDO::getProjectName,reqVO.getProjectName()));
        return respVO;
    }

    @Override
    public List<ProjectDO> selectProjectList(Collection<String> projectIds) {
        if(CollectionUtils.isEmpty(projectIds)) return new ArrayList<>();
        return projectMapper.selectBatchIds(projectIds);
    }

    private void validateProjectExists(String id) {
        if (projectMapper.selectById(id) == null) {
            throw exception(PROJECT_NOT_EXISTS);
        }
    }

    @Override
    public ProjectDO getProject(String id) {
        return projectMapper.selectById(id);
    }

    @Override
    public PageResult<ProjectDO> getProjectPage(ProjectPageReqVO pageReqVO) {
        return projectMapper.selectPage(pageReqVO);
    }

    @Override
    public void batchInsert(List<ProjectImportReqVO> list, boolean cover) {
        List<ProjectDO> addList = new ArrayList<>();
        List<ProjectDO> updateList = new ArrayList<>();
        AdminUserDO adminUserDO = adminUserService.getUser(WebFrameworkUtils.getLoginUserId());
        for(ProjectImportReqVO importReqVO : list){
            ProjectDO project = BeanUtil.toBean(importReqVO, ProjectDO.class,new CopyOptions().setIgnoreProperties("unitCode","constructionCode"));
            DeptDO deptDO = deptService.getDeptByOrgCode(importReqVO.getUnitCode());
            project.setUnitCode(deptDO.getId());
            project.setUnitName(deptDO.getName());
            if(StrUtil.isNotBlank(importReqVO.getConstructionName())){
                ManufacturerDO manufacturerDO = manufacturerService.getDeviceManufacturerByNameAndType(importReqVO.getConstructionName(),"2");
                if(manufacturerDO != null){
                    project.setConstructionCode(manufacturerDO.getId());
                    project.setConstructionName(manufacturerDO.getManufacturerName());
                }
            }
            LambdaQueryWrapper<ProjectDO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProjectDO::getProjectNo,project.getProjectNo()).or().eq(ProjectDO::getProjectName,project.getProjectName());
            queryWrapper.last("limit 1");
            ProjectDO projectDO = this.projectMapper.selectOne(queryWrapper);
            if(projectDO == null){
                project.setId(IdUtil.fastSimpleUUID());
                project.setUnitUser(adminUserDO.getNickname());
                project.setEnablingStatus(CommonStatusEnumx.ENABLE.getStatus());
                addList.add(project);
            }else{
                if(!cover) continue;
                BeanUtil.copyProperties(project,projectDO);
                updateList.add(projectDO);
            }
        }
        if(addList.size() > 0) this.projectMapper.insertBatch(addList);
        if(updateList.size() > 0) this.projectMapper.updateBatch(updateList);
    }

}